﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;

namespace ModbusTestTool.UI
{
    public partial class SerialControl : UserControl
    {
        /// <summary>
        /// This process takes some time to run so don't call it all the time
        /// </summary>
        static List<COMPortInfo> comInfo = COMPortInfo.GetCOMPortsInfo();

        /// <summary>
        /// Contains comports obtained already
        /// </summary>
        string[] comports = SerialPort.GetPortNames();

        /// <summary>
        /// This will setup the user interface
        /// </summary>
        /// <param name="comport"></param>
        public SerialControl(string comport, string modbusId, string baudrate)
        {
            InitializeComponent();

            this.ModbusId.Text = modbusId;
            this.Baud.Text = baudrate;


            
            
            //check to see if something has changed with comports then do get port info since its slow

            string [] tempcomports = SerialPort.GetPortNames();

            if (!Enumerable.SequenceEqual(comports, tempcomports))
            {
                comInfo = COMPortInfo.GetCOMPortsInfo();
                comports = tempcomports;
            }

            
            if (comports.Length-1 != comInfo.Count)
            {
                
            }


            string[] comport_plus_desc = new string[comInfo.Count];





            for (int i = 0; i < comInfo.Count; i++)
            {
                comport_plus_desc[i] = comInfo[i].Name + " " + comInfo[i].Description;

            }




            //comboBox1.DataSource = SerialPort.GetPortNames();

            ComPort.DataSource = comport_plus_desc;
            if (comport != string.Empty)
            {
                int index = findIndex(comport, comport_plus_desc);
                if (index != -1)
                {
                    ComPort.SelectedIndex = index;
                }
            }
            
        }

        int findIndex(string item, String[] list)
        {
            for (int i = 0; i < list.Length; i++)
            {
                if (list[i].Contains(item))
                    return i;
            }
            return -1;

        }
    }
}
